package test.mp.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import test.mp.domain.po.User;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName UserMapperTest2
 * @Description 条件构造器测试
 * @Author wxx
 * @Date 2024/08/12/23:29
 * @Version 1.0
 */
@SpringBootTest
public class UserMapperTest2 {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testQueryWrapper(){
        // 需求 查询出名字中带o的，存款大于等于1000元的用户id,username,info,balance 字段

        // 1. 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .select("id","username","info","balance")
                .like("username","o")
                .ge("balance","1000");
        // 2. 执行查询
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);

    }

    @Test
    public void testLambdaQueryWrapper(){
        // 需求 查询出名字中带o的，存款大于等于1000元的用户id,username,info,balance 字段

        // 1. 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .select(User::getId,User::getUsername,User::getInfo,User::getBalance)
                .like(User::getUsername,"o")
                .ge(User::getBalance,"1000");
        // 2. 执行查询
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);

    }


    @Test
    public void testUpdateByQueryWrapper(){
        // 需求 更新用户名为jack的用户余额为2000

        // 1. 要更新的数据
        User user = new User();
        user.setBalance(2000);
        // 2. 构建更新条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("username","Jack");
        // 3. 执行更新
        userMapper.update(user,queryWrapper);
    }



    @Test
    public void testUpdateWrapper(){
        // 需求 更新id为1,2,4的用户的余额，扣200
        List<String> ids = Arrays.asList("1","2","4");
        UpdateWrapper<User> id = new UpdateWrapper<User>().setSql("balance = balance - 200").in("id", ids);
        userMapper.update(null,id);

    }

    @Test
    public void testCustomSqlUpdate(){
        // 需求 更新id为1,2,4的用户的余额，扣200  自定义sql
        // 1.更新条件
        List<String> ids = Arrays.asList("1","2","4");
        int amount = 200;
        // 2.定义条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().in("id", ids);
        // 3.调用自定义sql方法
        userMapper.updateBalanceByIds(queryWrapper,amount);
    }

}
